<template>
	<view class="Lyric">
		<view class="container" ref="container">
			<view :style="offsetStyle">
				<view :class="{ active: index === currentIndex }" v-for="(item,index) in Lyric">
					{{item.txt}}
				</view>
				<view class="active" v-show="Lyric.length==0">本歌曲为纯音乐</view>
				<view>-</view>
			</view>
		</view>

		<AudioPlayer></AudioPlayer>
	</view>
</template>

<script setup>
	import {
		computed,
		ref,
		onMounted
	} from 'vue';
	import {
		onReady
	} from "@dcloudio/uni-app"
	import {
		GetLyric
	} from "@/utils/MusicAPI.js"
	const player = getApp().globalData.player
	const innerAudioContext = getApp().globalData.innerAudioContext
	const data = uni.getStorageSync('MusicUrl')
	const container = ref()
	const HeightArray = ref({
		liHeight: 30,
		containerHeight: 780
	})
	onReady(() => {
		getLyric(uni.getStorageSync("MusicUrl").songmid)
		HeightArray.value.containerHeight = container.value.$el.clientHeight
		HeightArray.value.liHeight = container.value.$el.children[0].children[0].clientHeight
	})
	// 存放歌词
	const Lyric = ref([])
	//计算高亮显示
	//如果没有任何一句歌词需要显示，则得到-1
	const currentIndex = computed(() => {
		const currentTime = player.value.currentTime * 1000
		const item = Lyric.value.find(item => item.time > currentTime)
		if (Lyric.value.indexOf(item) - 1 === -2) {
			return Lyric.value.length - 1
		} else {
			return Lyric.value.indexOf(item) - 1
		}
	})
	//设置 ul 的偏移量
	const offsetStyle = computed(() => {
		const liHeight = HeightArray.value.liHeight
		const containerHeight = HeightArray.value.containerHeight
		const index = currentIndex.value
		const offset = liHeight * index + liHeight / 2 - containerHeight / 2
		return `transform: translateY(${-offset}px)`
	})

	//获取歌曲歌词
	const getLyric = (songmid) => {
		GetLyric(songmid).then(res => {
			Lyric.value = res.data.response.lyric.lines
			uni.setNavigationBarTitle({
				title: uni.getStorageSync("MusicUrl").name
			})
		}).catch(err => {
			console.log("获取歌词错误", err)
		})
	}
</script>

<style scoped>
	page {
		background-color: #1b1b25;
	}

	.container {
		text-align: center;
		height: 80vh;
		line-height: 2em;
		overflow: hidden;
		color: #545454;

	}

	.container view {
		transition: 0.5s;
	}

	.active {
		color: #ffffff;
		transform: scale(1.1);
		font-weight: bold;
	}
</style>